﻿using System;
using System.IO;
using System.Net;
using System.Net;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml.Linq;

namespace CloudAppRestDemoWeb.Pages
{
    public partial class Default : System.Web.UI.Page
    {

        protected void Page_Load(object sender, EventArgs e)
        {

            // configure URL for link backk to host web
            linkHostSite.NavigateUrl = Page.Request["SPHostUrl"];

            // cache url to web app for other pages
            string appWebUrl = Page.Request["SPAppWebUrl"];
            Cache["SPAppWebUrl"] = appWebUrl;


            Uri uri = new Uri(appWebUrl + "/_api/web/?$select=Title");
            HttpWebRequest requestGet = (HttpWebRequest)WebRequest.Create(uri);
            requestGet.Credentials = CredentialCache.DefaultCredentials;
            requestGet.Method = "GET";
            HttpWebResponse responseGet = (HttpWebResponse)requestGet.GetResponse();
            XDocument doc = XDocument.Load(responseGet.GetResponseStream());
            XNamespace ns_dataservices = "http://schemas.microsoft.com/ado/2007/08/dataservices";
            lblAppWebTitle.Text = doc.Descendants(ns_dataservices + "Title").First().Value;

        }

        protected const string AtomXmlForNewList = @"
<entry 
	xmlns='http://www.w3.org/2005/Atom' 
	xmlns:d='http://schemas.microsoft.com/ado/2007/08/dataservices' 
	xmlns:m='http://schemas.microsoft.com/ado/2007/08/dataservices/metadata' >

  <category term='SP.List' 
            scheme='http://schemas.microsoft.com/ado/2007/08/dataservices/scheme' />
    
  <content type='application/xml'>
    <m:properties>
      <d:Title>@Title</d:Title>
      <d:BaseTemplate m:type='Edm.Int32'>@ListTypeId</d:BaseTemplate>
    </m:properties>
  </content>
</entry>";


        protected void cmdCreateNewList_Click(object sender, EventArgs e)
        {

            string ListTitle = txtNewListTitle.Text;
            if (string.IsNullOrEmpty(ListTitle))
            {
                lblStatus.Text = "ERROR: List title cannot be blank";
                return;
            }

            string ListType = lstListType.SelectedValue;

            string appWebUrl = Cache["SPAppWebUrl"].ToString();

            string FormDigest = GetFormDigest();

            Uri uri = new Uri(appWebUrl + "/_api/web/lists/");
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);

            request.Credentials = CredentialCache.DefaultCredentials;
            // set format of request body
            request.ContentType = "application/atom+xml";
            // set format of response body
            request.Accept = "application/atom+xml";
            request.Headers["X-RequestDigest"] = FormDigest;
            request.Method = "POST";

            string body = AtomXmlForNewList;
            body = body.Replace("@Title", EncodeXml(ListTitle));
            body = body.Replace("@ListTypeId", ListType);

            request.ContentLength = body.Length;
            StreamWriter writer = new StreamWriter(request.GetRequestStream());
            writer.Write(body);
            writer.Flush();

            try
            {
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                lblStatus.Text = "New " + lstListType.SelectedItem.Text +
                                  " list created with title of " + ListTitle;
            }
            catch (Exception ex)
            {
                lblStatus.Text = "ERROR: " + ex.Message;
            }

            // add client-side script to asychonously reload lists
            string updateScript = "$('#appweblists').load('/Pages/appWebLists.ashx');";
            ScriptManager.RegisterClientScriptBlock(upNewList, upNewList.GetType(), upNewList.ClientID, updateScript, true);

        }

        private string GetFormDigest()
        {
            string appWebUrl = Cache["SPAppWebUrl"].ToString();
            Uri uri = new Uri(appWebUrl + "/_api/contextinfo");
            HttpWebRequest requestPost = (HttpWebRequest)WebRequest.Create(uri);
            requestPost.Credentials = CredentialCache.DefaultCredentials;
            requestPost.Method = "POST";
            requestPost.ContentLength = 0;
            HttpWebResponse responsePost = (HttpWebResponse)requestPost.GetResponse();
            XDocument doc = XDocument.Load(responsePost.GetResponseStream());
            XNamespace ns_dataservices = "http://schemas.microsoft.com/ado/2007/08/dataservices";
            return doc.Descendants(ns_dataservices + "FormDigestValue").First().Value;

        }

        static public string EncodeXml(string XmlValue)
        {
            return XmlValue.Replace("&", "&amp;").Replace("<", "&lt;").Replace(">", "&gt;").Replace("\"", "&quot;").Replace("'", "&apos;");
        }

    }
}